package com.ruoyi.project.cardbox.inbound.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.project.cardbox.orders.domain.OrderStatus;
import com.ruoyi.project.cardbox.orders.domain.Orders;
import com.ruoyi.project.cardbox.orders.service.IOrdersService;
import com.ruoyi.project.cardbox.request.domain.OrderRequest;
import com.ruoyi.project.cardbox.request.service.IOrderRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.cardbox.inbound.mapper.OrderInboundMapper;
import com.ruoyi.project.cardbox.inbound.domain.OrderInbound;
import com.ruoyi.project.cardbox.inbound.service.IOrderInboundService;
import com.ruoyi.common.utils.text.Convert;

/**
 * 入库单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-04
 */
@Service
public class OrderInboundServiceImpl  extends ServiceImpl<OrderInboundMapper, OrderInbound> implements IOrderInboundService
{
    @Autowired
    private OrderInboundMapper orderInboundMapper;
    @Autowired
    private IOrderRequestService orderRequestService;
    @Autowired
    private IOrdersService ordersService;

    /**
     * 查询入库单
     * 
     * @param id 入库单主键
     * @return 入库单
     */
    @Override
    public OrderInbound selectOrderInboundById(Long id)
    {
        return orderInboundMapper.selectOrderInboundById(id);
    }

    /**
     * 查询入库单列表
     * 
     * @param orderInbound 入库单
     * @return 入库单
     */
    @Override
    public List<OrderInbound> selectOrderInboundList(OrderInbound orderInbound)
    {
        return orderInboundMapper.selectOrderInboundList(orderInbound);
    }

    /**
     * 新增入库单
     * 
     * @param orderInbound 入库单
     * @return 结果
     */
    @Override
    public int insertOrderInbound(OrderInbound orderInbound)
    {
        orderInbound.setCreateTime(DateUtils.getNowDate());
        return orderInboundMapper.insertOrderInbound(orderInbound);
    }

    /**
     * 修改入库单
     * 
     * @param orderInbound 入库单
     * @return 结果
     */
    @Override
    public int updateOrderInbound(OrderInbound orderInbound)
    {
        orderInbound.setUpdateTime(DateUtils.getNowDate());
        //如果入库数量大于订单数量，则返回错误
        if (orderInbound.getQuantity() != null && orderInbound.getQuantity() > orderInbound.getOrderQuantity()){
            throw new ServiceException("入库数量不能大于订单数量");
        }
        //如果入库数量和单价不为空，则计算金额
        if (orderInbound.getQuantity() != null && orderInbound.getUnitPrice() != null){
            orderInbound.setAmount(orderInbound.getUnitPrice().multiply(new BigDecimal(orderInbound.getQuantity())));
        }
        return orderInboundMapper.updateOrderInbound(orderInbound);
    }

    /**
     * 批量删除入库单
     * 
     * @param ids 需要删除的入库单主键
     * @return 结果
     */
    @Override
    public int deleteOrderInboundByIds(String ids)
    {
        String[] idArray = Convert.toStrArray(ids);
        int deleteCount = 0;

        for (String idStr : idArray) {
            Long id = null;
            try {
                id = Long.parseLong(idStr);
            } catch (NumberFormatException e) {
                // id格式不正确，跳过
                continue;
            }

            // 查询入库单，不存在跳过
            OrderInbound orderInbound=this.getById(id);
            if (orderInbound == null) {
                continue;
            }

            // 查询主订单，不存在跳过
            LambdaQueryWrapper<Orders> orderWrapper = new LambdaQueryWrapper<>();
            orderWrapper.eq(Orders::getOrderId, orderInbound.getOrderId());
            Orders order = ordersService.getOne(orderWrapper);
            if (order == null) {
                continue;
            }

            // 订单状态不是“请购”，跳过
            if (order.getStatus() != OrderStatus.IN_STOCK) {
                continue;
            }

            // 符合条件，删除请购单
            boolean removed = this.removeById(id);
            if (removed) {
                deleteCount++;
                // 更新主订单状态为草稿
                order.setStatus(OrderStatus.REQUESTED);
                ordersService.updateById(order);
            }
        }

        return deleteCount;
    }

    /**
     * 删除入库单信息
     * 
     * @param id 入库单主键
     * @return 结果
     */
    @Override
    public int deleteOrderInboundById(Long id)
    {
        return orderInboundMapper.deleteOrderInboundById(id);
    }

    @Override
    public void createInboundReceipt(Orders order) {
        if (order.getOrderId() == null) {
            throw new ServiceException("订单编号不能为空");
        }
        // 1. 根据 orderId 查询 OrderRequest 记录
        LambdaQueryWrapper<OrderRequest> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderRequest::getOrderId, order.getOrderId());
        OrderRequest orderRequest = orderRequestService.getOne(queryWrapper);
        if (orderRequest == null) {
            throw new RuntimeException("未找到对应的请购单");
        }
        //判断纸板信息是否存在
        // 2. 判断纸板信息是否完整（字段为空即视为不存在）
        if (orderRequest.getSizeLength() == null
                || orderRequest.getSizeWidth() == null
                || orderRequest.getOrderQuantity() == null
                || orderRequest.getUnitPrice() == null
                || orderRequest.getFluteType() == null
                || orderRequest.getLayerCount() == null){
            throw new ServiceException("请购单缺少纸板信息，无法生成入库单");
        }

        // 3. 构建 OrderInbound 实体并设置属性
        OrderInbound orderInbound = new OrderInbound();
        orderInbound.setOrderId(order.getOrderId());
        orderInbound.setCustomerName(order.getCustomerName());
        orderInbound.setProductName(order.getProductName());
        orderInbound.setSpecs(orderRequest.getSpecs());
        orderInbound.setSizeLength(orderRequest.getSizeLength());
        orderInbound.setSizeWidth(orderRequest.getSizeWidth());
        orderInbound.setOrderQuantity(orderRequest.getOrderQuantity());
        orderInbound.setUnitPrice(orderRequest.getUnitPrice());
        orderInbound.setFluteType(orderRequest.getFluteType());
        orderInbound.setLayerCount(orderRequest.getLayerCount());

        orderInbound.setCreateTime(DateUtils.getNowDate());
        orderInbound.setUpdateTime(DateUtils.getNowDate());

        // 4. 保存入库单
        this.save(orderInbound);
    }

    @Override
    public List<OrderInbound> selectOrderInboundByIds(List<String> ids) {
        return orderInboundMapper.selectOrderInboundByIds(ids);
    }
}
